package com.jf.identity.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.annotation.Resource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * @author FCG
 */
@Component
@Aspect
@Order(1)
public class AtomikosTransactionAop {
    @Resource
    private JtaTransactionManager jtaTransactionManager;
    @Resource(name = "userTransactionImp")
    private UserTransaction userTransaction;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Around(value = "@annotation(com.jf.identity.aop.AtomikosTransaction)")
    public Object transaction(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
//        UserTransaction userTransaction = jtaTransactionManager.getUserTransaction();
        Object object;
        try {
            logger.debug("{} 方法,开启事务", methodName);
            userTransaction.begin();
            object = joinPoint.proceed();
            userTransaction.commit();
            logger.debug("{} 方法,提交事务", methodName);
        } catch (Throwable throwable) {
            logger.debug("{} 方法，回滚事务", methodName);
            try {
                userTransaction.rollback();
            } catch (SystemException e) {
                logger.warn(e.getMessage(), e);
            }
            throw new Throwable(throwable);

        }
        return object;
    }

}
